package com.holy.sh.module_base_mvp.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.util.Map;

/**
 * SharedPreferences 管理类
 * Created by Alpha on 2016/4/26.
 */
public class SpfHelper {
    /**
     * keys
     */
    public static final String CART_CITYS = "cart_citys";


    private SharedPreferences sp;

    private SharedPreferences.Editor editor;

    public SpfHelper(Context context, String name) {
        this.sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        editor = sp.edit();
    }

    public SpfHelper saveNoCommit(String key, Object value) {
        if (value instanceof String) {
            editor.putString(key, TextUtils.isEmpty((String) value) ? "" : (String) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        }
        return this;
    }

    public void apply() {
        if (editor != null) {
            editor.apply();
        }
    }

    public String getString(String key) {
        return sp.getString(key, "");
    }

    public String getString(String key, String defaule) {
        return sp.getString(key, defaule);
    }

    public int getInt(String key) {
        return sp.getInt(key, 0);
    }

    public Boolean getBoolean(String key) {
        return sp.getBoolean(key, false);
    }

    public <T> T getValue(String strName) {
        Map<String, ?> values = sp.getAll();

        if (values.get(strName) != null) {
            return (T) values.get(strName);
        } else {
            return null;
        }
    }

}
